package dao;

import java.io.IOException;
import java.io.Serializable;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;

import persistence.Activity;
import persistence.Clients_has_Firm;
import persistence.Email;
import persistence.Filling;
import persistence.Firm;
import persistence.FirmPK;
import persistence.Firm_has_Account;
import persistence.Firm_has_Assest;
import persistence.Firm_has_Employee;
import persistence.Firm_has_Owner;
import persistence.Service;
import persistence.Structuredria_BetaRequest;
import persistence.Wrap;

import javax.portlet.*;



@ManagedBean(name="firmDao")
@SessionScoped
public class FirmDao extends org.portletfaces.bridge.GenericFacesPortlet implements Serializable {


		   
			private static final long serialVersionUID = 1L;
			/**
			 * 
			 */
			private static final String JPA_UNIT_NAME = "User";
			private static final String JPA_UNIT_NAME2 = "User2";
			private static EntityManager entityManager;
			private static EntityManager entityManager2;
			List<Firm> firms;
			static Firm firmIdCrd;
			Firm firm;
			String contextPath;
            String strXml;
            boolean sortAscending=true;
            static boolean refresh=false;
            

				public String getStrXml() {
					/*String xml = "  <chart caption='Monthly Unit Sales' xAxisName='Month' yAxisName='Units' showValues='0' formatNumberScale='0' showBorder='1'>";
						      xml += "<set label='Jan' value='462' />";
						      xml += "<set label='Feb' value='857' />";
						      xml += "<set label='Mar' value='671' />";
						      xml += "<set label='Apr' value='494' />";
						      xml += "<set label='May' value='761' />";
						      xml += "<set label='Jun' value='960' />";
						      xml += "<set label='Jul' value='629' />";
						      xml += "<set label='Aug' value='622' />";
						      xml += "<set label='Sep' value='376' />";
						      xml += "<set label='Oct' value='494' />";
						      xml += "<set label='Nov' value='761' />";
						      xml += "<set label='Dec' value='960' />";
						      xml += "</chart>";
						    */
						     String xml=" <chart caption='Types of Clients in Percentage' showLegend='1' legendPosition='BOTTOM' >"
						      +"<set label='Services' value='26' />"
						      +"<set label='Hardware' value='32' />"
						      +"<set label='Software' value='42' />"
						      +"</chart>";



				return xml;
			}

			public void setStrXml(String strXml) {
				this.strXml = strXml;
			}

				protected EntityManager getEntityManager() {
					if (entityManager == null)
					{
						entityManager = Persistence.createEntityManagerFactory(
								JPA_UNIT_NAME).createEntityManager();
					}
					
					return entityManager;
				}
				
				protected EntityManager getEntityManager2() {
					if (entityManager2 == null)
					{
						entityManager2 = Persistence.createEntityManagerFactory(
								JPA_UNIT_NAME2).createEntityManager();
					}
					
					return entityManager2;
				}
				
				
				public Structuredria_BetaRequest getMail(int idFirm,int crd)
			    {
				
				
			    
			    Structuredria_BetaRequest s1=new Structuredria_BetaRequest();
			    s1.setRequestId("1");
			    
			    
			    this.getEntityManager2().getTransaction().begin();
				s1=this.getEntityManager2().find(Structuredria_BetaRequest.class,"1");
				this.getEntityManager2().getTransaction().commit();
				System.out.println("getting mail="+"  "+s1.getEmailAddress());
				
			    
				return s1;
				   	
			    	
			    }
				

				
				
				public static boolean isRefresh() {
					return refresh;
				}

				public static void setRefresh(boolean refresh) {
					FirmDao.refresh = refresh;
				}

				public List<Firm> selectAll() {
					List<Firm> firms = getEntityManager().createQuery(
							"select p from Firm p").getResultList();
					return firms;
				}

				public List<Firm> getFirms() {
						return  this.selectAll();
				}

				public void setFirms(List<Firm> firms) {
					this.firms = firms;
					
				}
				
				public void addUser()
				{
					this.getEntityManager().getTransaction().begin();
					this.getEntityManager().persist(this.getFirm());
					this.getEntityManager().getTransaction().commit();
					
				}
				
			    public Firm getFirm() {
					return firm;
				}

				public void setFirm(Firm firm) {
					this.firm = firm;
				}

				public Firm firmIdCrd(int idFirm,int crd)
			    {
				
				if(firmIdCrd==null)
			    {System.out.println("Firm id crd is null");
			    FirmPK pk=new FirmPK();
			    pk.setCrd(crd);
			    pk.setIdFirm(idFirm);
			    this.getEntityManager().getTransaction().begin();
				firmIdCrd=this.getEntityManager().find(Firm.class,pk);
				this.getEntityManager().getTransaction().commit();
				System.out.println("getting firmidcrd");
				}
			    else System.out.println("Firm id crd is not null");
				return firmIdCrd;
				   	
			    	
			    }
				
				public String getSumAssUndMgm(int idFirm,int crd)
				{
					Firm firm=this.firmIdCrd(idFirm,crd);
				Set<Firm_has_Assest> clientsHasAssests=firm.getFirmHasAssests();
				int sum=0;
				for(Firm_has_Assest cliHasAssest:clientsHasAssests)
				{sum=sum+cliHasAssest.getAuuAmount().intValue();
								
					
				}
				String result=String.valueOf(sum);
				String temp = "";int cmpt=0;
				if(result.length()>3)
				{
					for(int i=0;i!=result.length();i++)
					{temp=result.charAt(result.length()-1-i)+temp;
					cmpt++;
					if((cmpt==3) && ( result.length()-1-i)!=0){temp=","+temp;cmpt=0;}
					}
				
									
				}
				else temp=result;
				
					return temp;
				}
		

                public List <Service> getServices(int idFirm,int crd)
                {
					Firm firm=this.firmIdCrd(idFirm,crd);
                    Set <Service> services=firm.getServices();
                    List <Service> listServ=new ArrayList<Service>();
                    for(Service service:services)
                    {listServ.add(service);
                    System.out.println(service.getServiceName());
                    }
                    return listServ;
                	
                }
                
                public List <Activity> getActivities(int idFirm,int crd)
                {
					Firm firm=this.firmIdCrd(idFirm,crd);
                    Set <Activity> activities=firm.getActivities();
                    List <Activity> listActiv=new ArrayList<Activity>();
                    for(Activity activity:activities)
                    {listActiv.add(activity);
                   // System.out.println(activity.getActivName());
                    }
                    return listActiv;
                	
                }
                
                public  String getClients(int idFirm,int crd)
                {
                	Firm firm=this.firmIdCrd(idFirm,crd);
                	Set <Clients_has_Firm> clientsFirms=firm.getClientsHasFirms();
                	for(Clients_has_Firm cliFirm:clientsFirms)
                	{
                		//System.out.println("Client type :"+cliFirm.getClient().getType()+" Rate="+cliFirm.getRate());
                		
                	}
                	return "YES";
                	
                }
                
                public  String getEmployees(int idFirm,int crd)
                {
                	Firm firm=this.firmIdCrd(idFirm,crd);
                	Set <Firm_has_Employee> employeesFirms=firm.getFirmHasEmployees();
                	for(Firm_has_Employee firmEmpl:employeesFirms)
                	{
               // System.out.println("Employee type :"+firmEmpl.getEmployee().getType()+" Rate="+firmEmpl.getNumber());
                		
                	}
                	return "YES";
                	
                }

                public String getAssUnderMgmt(int idFirm,int crd)
                {
                	Firm firm=this.firmIdCrd(idFirm,crd);
    				Set<Firm_has_Assest> firmHasAssests=firm.getFirmHasAssests();
    				
    				for(Firm_has_Assest fAsst:firmHasAssests)
    				{
    					//System.out.println("Type Assest="+fAsst.getAssest().getAumType()+" Amount="+fAsst.getAuuAmount().intValue());
    					
    				}
                         // System.out.println("Total="+this.getSumAssUndMgm(idFirm, crd));
                          
                          return "YES";
                	
                }


		/*public String getNbrAccounts(int idFirm,int crd)
		{
			
			Firm firm=this.firmIdCrd(idFirm,crd);
			
			Set<Firm_has_Account> firmHasAccounts=firm.getFirmHasAccounts();
			int sum=0;
			for(Firm_has_Account firmAcc:firmHasAccounts)
			{
				//System.out.println("Type Account="+firmAcc.getAccount().getType()+" Amount="+firmAcc.getQtte());
				sum=sum+firmAcc.getQtte();
			}

			
			//System.out.println("Total="+sum);
			return "Yes";
			
		}*/
		


		public List<Wrap> getWraps(int idFirm,int crd)
		{
			Firm firm=this.firmIdCrd(idFirm,crd);
			Set<Wrap> wraps=firm.getWraps();
			System.out.println("Wraps="+wraps.size());
			List<Wrap> wrapsExp=new ArrayList<Wrap>();
			for(Wrap wrap:wraps)
			{wrapsExp.add(wrap);
				
			}
			
			return wrapsExp;
		}
		
		public List<Firm_has_Owner> getOwners(int idFirm,int crd,byte isDirect)
		{
			Firm firm=this.firmIdCrd(idFirm,crd);
            Set<Firm_has_Owner> owners=firm.getFirmHasOwners();
            List<Firm_has_Owner> ownersExpDir=new ArrayList<Firm_has_Owner>();
            List<Firm_has_Owner> ownersExpInd=new ArrayList<Firm_has_Owner>();
            
            for(Firm_has_Owner firmhasOwn:owners)
            {
            //System.out.println("Direct Owner :"+firmhasOwn.getPr());
            //System.out.println("Owner mail:"+firmhasOwn.getOwner().getEmail());
            if(firmhasOwn.getPr()==1)
            {ownersExpDir.add(firmhasOwn);
            	
            }
            else ownersExpInd.add(firmhasOwn);
            
            	
            }
			if(isDirect==1)return ownersExpDir;
			else return ownersExpInd;
			
		}
		public String getContextPath()
		{
			return "FirmsDb-portlet";
			
						
			
		}
		@Override
	    public void doView(RenderRequest request, RenderResponse response) throws IOException, PortletException 
			{ super.doView(request, response);
			
					
			}
		
		@Override
	    public void processAction(
	            ActionRequest actionRequest, ActionResponse actionResponse)
	        throws IOException, PortletException {
		System.out.println("Action="+actionRequest.getMethod());
			super.processAction(actionRequest, actionResponse);
			
		}
		
		
		
		public String getTypeClients(int idFirm,int crd) throws ParseException
		{  Firm firm=this.firmIdCrd(idFirm,crd);
		   Set<Clients_has_Firm> firmClients=firm.getClientsHasFirms();
		   String xml=" <chart caption='Types of Clients in Percentage' showLegend='1' legendPosition='BOTTOM' showPercentValues='1' showPercentInToolTip='1' showValues='1' showLabels='0' showToolTip='1'>";
           HashMap<String,Double> typeClients=new HashMap<String,Double>();
		   Pattern r = Pattern.compile("(.*)(\\d\\d)(%)");
		   double sum=0;
           DecimalFormat form = new java.text.DecimalFormat( "0.0" ); 
			Matcher m ;
			for(Clients_has_Firm cliFirm:firmClients)
			{
			
			  m= r.matcher(cliFirm.getRate());
				if(m.find())
				{
				
				typeClients.put(cliFirm.getClient().getType().trim(), Double.parseDouble(m.group(2)));
				sum=sum+Double.parseDouble(m.group(2));	
				System.out.println("sum="+sum);
				}
				else System.out.println("Rate not matched !");
			}
			
		   //Sum calculated
			
		  		   
			for(Entry<String,Double> entry:typeClients.entrySet())
		   {
			   entry.setValue(form.parse(form.format((entry.getValue()/sum)*100)).doubleValue());
			  
			   xml=xml+"<set label='"+entry.getKey()+"' value='"+entry.getValue()+"' />";
			      
			   
		   }

			return xml+"</chart>";
		}
		
			
		public String getNbrEmployees(int idFirm,int crd) throws ParseException
		{Firm firm=this.firmIdCrd(idFirm,crd);
		   Set<Firm_has_Employee> firmEmployees=firm.getFirmHasEmployees();
		   String xml=" <chart caption='Number of Employees' showLegend='1' legendPosition='BOTTOM' showPercentValues='1' showPercentInToolTip='1' showValues='1' showLabels='0' showToolTip='1'>";
           HashMap<String,Double> nbrEmployees=new HashMap<String,Double>();
		   Pattern r = Pattern.compile("(\\d+)(-)(.*)");
		   double sum=0;
           DecimalFormat form = new java.text.DecimalFormat( "0.0" ); 
			Matcher m ;
			String commString="";
			for(Firm_has_Employee firmEmpl:firmEmployees)
			{
				m=r.matcher(firmEmpl.getNumber());
				if(m.find())
				{
				System.out.println("Number="+m.group());
				System.out.println("Number1="+m.group(1));
				nbrEmployees.put(firmEmpl.getEmployee().getType().trim(), Double.parseDouble(m.group(1)));
				commString=m.group(3);
				commString=commString.replaceAll(",","");
				
				sum=sum+Double.parseDouble(commString);	
				System.out.println("sum="+sum);
				}
				else System.out.println("Nbr not matched !");
						
			}
			
			//Sum calculated
			
	  		   
			for(Entry<String,Double> entry:nbrEmployees.entrySet())
		   {
			   System.out.println("oldVal="+entry.getValue());
				entry.setValue(form.parse(form.format((entry.getValue()/sum)*100)).doubleValue());
			  
			   xml=xml+"<set label='"+entry.getKey()+"' value='"+entry.getValue()+"' />";
			      
			   
		   }

			return xml+"</chart>";

				
		}
		
		public String getAssUndMgmt(int idFirm,int crd)
		{Firm firm=this.firmIdCrd(idFirm,crd);
		Set<Firm_has_Assest> firm_Has_Assests=firm.getFirmHasAssests();
		HashMap<String,String> firmAssests=new HashMap<String,String>();
		String xml=" <chart caption='Assets Under Management' showPercentValues='1' showPercentInToolTip='1' showValues='1'  showToolTip='1' xAxisName='Type' yAxisName='Amount' numberPrefix='$' showLabels='1' formatNumberScale='0'>";
		int sum=0;
		
		for(Firm_has_Assest firmAss:firm_Has_Assests)
		{
			firmAssests.put(firmAss.getAssest().getAumType(),firmAss.getAuuAmount().toString());
			sum=sum+Integer.parseInt(firmAss.getAuuAmount().toString());
			
		}
		firmAssests.put("Total",String.valueOf(sum));
		//Sum calculated
		for(Entry<String,String> entry:firmAssests.entrySet())
		{   System.out.println("Before Key="+entry.getKey()+"  value="+entry.getValue());
			//entry.setValue(Double.toString((Double.parseDouble(entry.getValue())/sum)*100));
			System.out.println("After Key="+entry.getKey()+"  value="+entry.getValue());
			if(!entry.getKey().contains("Total"))xml=xml+"<set label='"+entry.getKey()+"' value='"+entry.getValue().replaceAll(",",".")+"' />";
		}
		xml=xml+"<set label='"+"Total"+"' value='"+firmAssests.get("Total").replaceAll(",",".")+"' />";
		
		
		return xml+"</chart>";
		}
		
		
		public String getNbrAccounts(int idFirm,int crd)
		{Firm firm=this.firmIdCrd(idFirm,crd);
		Set<Firm_has_Account> firm_Has_Accounts=firm.getFirmHasAccounts();
		HashMap<String,String> firmAccounts=new HashMap<String,String>();
		String xml=" <chart caption='Number of Accounts' showPercentValues='1' showPercentInToolTip='1' showValues='1'  showToolTip='1' xAxisName='Type' yAxisName='Amount' showLabels='1' >";
		int sum=0;
		
		for(Firm_has_Account firmAcc:firm_Has_Accounts)
		{
			firmAccounts.put(firmAcc.getAccount().getType(),String.valueOf(firmAcc.getQtte()));
			sum=sum+firmAcc.getQtte();
			
		}
		//sum claculated
		firmAccounts.put("Total",String.valueOf(sum));
		
		for(Entry<String,String> entry:firmAccounts.entrySet())
		{   System.out.println("Before Key="+entry.getKey()+"  value="+entry.getValue());
			//entry.setValue(Double.toString((Double.parseDouble(entry.getValue())/sum)*100));
			System.out.println("After Key="+entry.getKey()+"  value="+entry.getValue());
			if(!entry.getKey().contains("Total"))xml=xml+"<set label='"+entry.getKey()+"' value='"+entry.getValue().replaceAll(",",".")+"' />";
		}
		xml=xml+"<set label='"+"Total"+"' value='"+firmAccounts.get("Total").replaceAll(",",".")+"' />";
		
		
		return xml+"</chart>";
		
		}
		
		public List<String> formatCompensation(int idFirm,int crd)
		{Firm firm=this.firmIdCrd(idFirm,crd);
		String[] listComp;
		String compensation=firm.getCompensation();
		String temp;
		listComp=compensation.split("(\\s*\\(\\d+\\)\\s*)");
		List<String> retList=new ArrayList<String>();
		for(int i=0;i!=listComp.length;i++)
		{
	    System.out.println("Comp Split1="+listComp[i]);
	    temp=listComp[i].trim();
		if(temp.length()>=1)
	    {
		if(temp.charAt(1)==','){temp=temp.substring(1,temp.length()-1);}
		if(temp.charAt(temp.length()-1)==','){temp=temp.substring(0,temp.length()-2);}
	    }
		
		
		
		if(!temp.trim().equals("")) retList.add(temp);
		
		System.out.println("Comp Split2="+temp);
			
		}
		
		return retList;
		
					
			
		}
		
		public String getMapDatas(int idFirm,int crd)
		{Firm firm=this.firmIdCrd(idFirm,crd);
		Set<Filling> list=firm.getFillings();
		System.out.println("#Filling");	
		for(Filling f:list)
			{
				System.out.println(f.getStateFilling());
			}
			String xml= "<map   borderColor='005879' fillColor='D7F4FF' showLegend='1' showCanvasBorder='0' legendPosition='BOTTOM' numberSuffix=' Filed' includeValueInLabels='0' labelSepChar=': ' showLabels='1' baseFontSize='9'>"
					
					+"<colorRange>  <color minValue='1' maxValue='1' displayValue='Filed' color='0066FF' />"+
					
					"</colorRange><data>";
					for(Filling f:list)
					{
						xml=xml+"<entity id='"+f.getStateFilling()+"'"+"value='1' color='0066FF'/>";
					}
			      
					xml=xml+"</data></map>";
					
					System.out.println("#Filling size="+list.size());
					
					return xml;
			
			
			
			
			
		}
		
		public String firmGetAddress2(int idFirm,int crd)
		{String address2="";
		Firm firm=this.firmIdCrd(idFirm,crd);
		address2=address2+firm.getFirmAddress().getCity()+","+
	    firm.getFirmAddress().getState()+" "+firm.getZipcode();
		return address2;	
			
			
		}
		
		public String toGoogle(int idFirm,int crd)
		{Firm firm=this.firmIdCrd(idFirm,crd);
		String adress="";
		adress=adress+firm.getAddress();
		adress=adress+" "+firmGetAddress2(idFirm,crd);
		adress=adress+" "+firm.getFirmAddress().getCountry();
		adress=adress.trim().replaceAll("\\s+","+");
			System.out.println("Address to google"+adress);
			return adress;
		}
		public static void refresh()
		{
		if(FirmDao.entityManager!=null)
			{FirmDao.entityManager=null;
			FirmDao.firmIdCrd=null;
			}
		}
		@Override
		public void render(RenderRequest request,RenderResponse response)
		{
			try {FirmDao.refresh();
				super.render(request, response);
				
			} catch (PortletException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}}

		public Firm getFirmIdCrd() {
			return firmIdCrd;
		}

		public void setFirmIdCrd(Firm firmIdCrd) {
			this.firmIdCrd = firmIdCrd;
		}
		
		public String getRegionName(String code)
		{
			
			if(code.equals("AL"))
				return "";
			else if (code.equals("AK"))
				return "Alaska";
			else if (code.equals("AZ"))
				return "Arizona";
			else if (code.equals("AR"))
				return "Arkansas";
			else if (code.equals("CA"))
				return "California";
			else if (code.equals("CO"))
				return "Colorado";
			else if (code.equals("CT"))
				return "Connecticut";
			else if (code.equals("DE"))
				return "Delaware";
			else if (code.equals("DC"))
				return "District of Columbia";
			else if (code.equals("FL"))
				return "Florida";
			else if (code.equals("GA"))
				return "Georgia";
			else if (code.equals("HI"))
				return "Hawaii";
			else if (code.equals("ID"))
				return "Idaho";
			else if (code.equals("IL"))
				return "Illinois";
			else if (code.equals("IN"))
				return "Indiana";
			else if (code.equals("IA"))
				return "Iowa";
			else if (code.equals("KS"))
				return "Kansas";
			else if (code.equals("KY"))
				return "Kentucky";
			else if (code.equals("LA"))
				return "Louisiana";
			else if (code.equals("ME"))
				return "Maine";
			else if (code.equals("MD"))
				return "Maryland";
			else if (code.equals("MA"))
				return "Massachusetts";
			else if (code.equals("MI"))
				return "Michigan";
			else if (code.equals("MN"))
				return "Minnesota";
			else if (code.equals("MS"))
				return "Mississippi";
			else if (code.equals("MO"))
				return "Missouri";
			else if (code.equals("MT"))
				return "Montana";
			else if (code.equals("NE"))
				return "Nebraska";
			else if (code.equals("NV"))
				return "Nevada";
			else if (code.equals("NH"))
				return "New Hampshire";
			else if (code.equals("NJ"))
				return "New Jersey";
			else if (code.equals("NM"))
				return "New Mexico";
			else if (code.equals("NY"))
				return "New York";
			else if (code.equals("NC"))
				return "North Carolina";
			else if (code.equals("ND"))
				return "North Dakota";
			else if (code.equals("OH"))
				return "Ohio";
			else if (code.equals("OK"))
				return "Oklahoma";
			else if (code.equals("OR"))
				return "Oregon";
			else if (code.equals("PA"))
				return "Pennsylvania";
			else if (code.equals("RI"))
				return "Rhode Island";
			else if (code.equals("SC"))
				return "South Carolina";
			else if (code.equals("TN"))
				return "Tennessee";
			else if (code.equals("SD"))
				return "South Dakota";
			else if (code.equals("TX"))
				return "Texas";
			else if (code.equals("UT"))
				return "Utah";
			else if (code.equals("VT"))
				return "Vermont";
			else if (code.equals("VA"))
				return "Virginia";
			else if (code.equals("WA"))
				return "Washington";
			else if (code.equals("WI"))
				return "Wisconsin";
			else if (code.equals("WY"))
				return "Wyoming";
			else if (code.equals("AS"))
				return "American Samoa";
			else if (code.equals("GU"))
				return "Guam";
			else if (code.equals("MP"))
				return "Northern Mariana Islands";
			else if (code.equals("GU"))
				return "Guam";
			else if (code.equals("PR"))
				return "Puerto Rico";
			else if (code.equals("VI"))
				return "Virgin Islands";
			else if (code.equals("UM"))
				return "U.S. Minor Outlying Islands";
			else if (code.equals("FM"))
				return "Federated States of Micronesia";
			else if (code.equals("MH"))
				return "Marshall Islands";
			else if (code.equals("AP"))
				return "Pacific";
			else if (code.equals("CZ"))
				return "Canal Zone";
			else if (code.equals("PI"))
				return "Philippine Islands";
			else if (code.equals("TT"))
				return "Trust Territory of the Pacific Islands";
			else if (code.equals("CM"))
				return "Commonwealth of the Northern Mariana Islands";
			else if (code.equals("WV"))
				return "West Virginia";
			else return "";
		
		}
		
		public String getGoogleMapFilling(int idFirm,int crd)
		{
		Firm firm=this.firmIdCrd(idFirm,crd);
		Set<Filling> list=firm.getFillings();
		String output="[";
		for(Filling f:list)
		{
			output=output+"['"+f.getStateFilling()+"','"+this.getRegionName(f.getStateFilling())+"',1],";
		
		}
		output=output.substring(0,output.length()-1)+"]";
		System.out.println("Dexter========="+output);
		return output;
		
		
		}
		
		public List<Email> getAllFirmsEmails(int test)
		{
			
				List<Email> firms_emails = getEntityManager().createQuery(
						"select p from emails p").getResultList();
				for (Email e : firms_emails)
				{
					System.out.println("Mail:"+e.getEmail()+" Firm:="+e.getFirm().getLegName());
					
				}
				return firms_emails;
			
			
		}
		
		
		
}